package com.googlecode.allinclusive.fw.web.struts2.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.googlecode.allinclusive.fw.web.valueobject.ResultMessageObject;
import com.googlecode.allinclusive.fw.web.valueobject.UserObject;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;

/**
 * 会话拦截处理
 */
@SuppressWarnings("serial")
public class SessionInterceptor extends UrlActionInterceptor {
	
	/** 会话过期的消息ID*/
	public static final String CMNI10001 = "CMNI10001";
	public static final String CMNE10001 = "CMNE10001";
	
    /** 会话过期的跳转页面*/
    protected String redirect = "login";
	
	/**
	 * 会话拦截处理
	 */
	public String doIntercept(ActionInvocation invocation) throws Exception {
        
		// 请求的URL路径
        ActionContext ac = invocation.getInvocationContext();
        HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
        final String requestURI = request.getRequestURI();
        
        // 登录用户
        Map<String, Object> sess = ac.getSession();
        UserObject userObject = (UserObject) sess.get(UserObject.USER_OBJECT_KEY);
		if (userObject == null) {
			// TODO Message Code ?
			// 未登录/会话过期，跳转到指定页面
			ResultMessageObject resultMessage = new ResultMessageObject(requestURI, CMNI10001, CMNE10001);
			sess.put(ResultMessageObject.RESULT_MESSAGE_KEY, resultMessage);
			return redirect;
		} else {
			return invocation.invoke();
		}
	}

	/**
	 * 会话过期的跳转页面
	 * @param redirect 跳转页面
	 */
	public void setRedirect(String redirect) {
		this.redirect = redirect;
	}
}